package com.taxis.service;

import java.util.List;
import org.hibernate.*; 
import com.taxis.common.*;
import com.taxis.model.Peticion;
import com.taxis.model.Reporte;

public class ReporteDaoService {

	private List<Reporte> reportes;
	private Reporte reporte;
	private Peticion peticion;
	
	public ReporteDaoService(){ }

	public void insertReporte(Reporte r) throws Exception{
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			session.save(r);
			peticion = (Peticion)session.get(Peticion.class, r.getPeticion().getIdPeticion());
			peticion.setEstado("Atendida");
			session.update(peticion);
			tx.commit();
		}catch(RuntimeException re){
			if(r != null){
				tx.rollback();
			}
			throw re;
		}finally{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Reporte> getAllReportes() {
		Session session = HibernateUtil.currentSession();
		try {
			Query q = session.getNamedQuery("getAllReportes");
			reportes = (List<Reporte>)q.list();
			return reportes;
		} catch(Exception e) {
			System.out.println("Error while fetching REPORTES");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}

	public Reporte getReporte(Integer idReporte) throws Exception {
		Session session = HibernateUtil.currentSession();
		try {
			return (Reporte)session.get(Reporte.class, idReporte);
		} finally {
			session.close();
		}
	}

	public void updateReporte(Reporte r) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(r);
			tx.commit();
		} catch(RuntimeException re) {
			if(r != null)
				tx.rollback();
			throw re;
		} finally {
			session.close();
		}
	}

	public void deleteReporte(Integer idReporte) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			reporte = (Reporte)session.load(Reporte.class, idReporte);
			session.delete(reporte);
			tx.commit();
		} catch (RuntimeException e) {
			if(reporte != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	@SuppressWarnings("unchecked")
	public Reporte findByPeticion(Integer idpeticion) {
		Session session = HibernateUtil.currentSession();
		try {
			SQLQuery query = session.createSQLQuery("SELECT * from reporte inner join peticion on reporte.id_peticion = peticion.id_peticion where peticion.id_peticion =:idpeticion");
			query.addEntity(Reporte.class);
			query.setInteger("idpeticion",idpeticion);
			Reporte r = (Reporte)query.uniqueResult();
			return r;
		} catch(Exception e) {
			System.out.println("Error while fetching REPORTE");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}
}